<template>
  <div>
    <el-dialog
      :title="isFjOrJs == 'NC' ? '添加企业' : '添加项目'"
      :visible.sync="centerDialogVisible"
      width="900px"
      :before-close="dialogClose"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
    >
      <el-form
        :inline="true"
        ref="searchConditions"
        style="padding-top: 8px"
        label-width="95px"
      >
        <el-form-item :label="isFjOrJs == 'NC' ? '企业区域' : '项目区域'">
          <el-cascader
            v-model="area"
            :options="areasOptions"
            @change="getAreaId"
            clearable
            filterable
            placeholder="请选择"
            :props="{ checkStrictly: true }"
            class="dialogDoubleInp"
            :append-to-body="false"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="所属行业">
          <el-select
            clearable
            filterable
            multiple
            placeholder="请选择(可多选)"
            class="dialogDoubleInp"
            v-model="industryId"
            v-if="isFjOrJs == 'CS'"
            :popper-append-to-body="false"
          >
            <el-option
              v-for="item in industryOptions"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            >
            </el-option>
          </el-select>
          <!-- <el-select v-model="industryId" filterable clearable multiple  placeholder="请选择(可多选)" class = "dialogDoubleInp" v-else>
                    <el-option
                        v-for="item in ncIndustryOptions"
                        :key="item.id"
                        :label="item.industryName"
                        :value="item.id"
                    ></el-option>
                </el-select> -->
          <el-cascader
            ref="industry"
            v-model="industryId"
            :options="industryOptionsNC"
            @change="getIndustryId"
            :props="propsArr"
            filterable
            placeholder="请选择(可多选)"
            collapse-tags
            :append-to-body="false"
            class="dialogDoubleInp"
            v-else
          ></el-cascader>
        </el-form-item>
        <template v-if="advanced">
          <el-form-item
            label="投资类型"
            class="row-padding-bottom"
            v-if="isFjOrJs == 'CS'"
          >
            <el-select
              clearable
              filterable
              multiple
              placeholder="请选择(可多选)"
              class="dialogDoubleInp"
              v-model="investment"
              :popper-append-to-body="false"
            >
              <el-option
                v-for="item in investmentOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="状态"
            class="row-padding-bottom"
            v-if="isFjOrJs == 'CS'"
          >
            <el-select
              v-model="filterField.status"
              filterable
              placeholder="请选择"
              class="dialogDoubleInp"
              clearable
              :popper-append-to-body="false"
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="项目评级"
            class="row-padding-bottom"
            v-if="isFjOrJs == 'CS'"
          >
            <el-select
              clearable
              filterable
              multiple
              placeholder="请选择(可多选)"
              class="dialogDoubleInp"
              v-model="gradeLevel"
              :popper-append-to-body="false"
            >
              <el-option
                v-for="item in proGradeArr"
                :key="item.gradeLevel"
                :label="item.name"
                :value="item.gradeLevel"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            :label="isFjOrJs == 'NC' ? '单位名称' : '项目名称'"
            class="row-padding-bottom"
          >
            <el-input
              v-model.trim="projectName"
              :placeholder="
                isFjOrJs == 'NC' ? '请输入单位名称' : '请输入项目名称'
              "
              class="dialogDoubleInp"
              clearable
            ></el-input>
          </el-form-item>
        </template>
        <el-form-item label="">
          <a
            @click="toggleAdvanced"
            style="margin-left: 40px; color: #409eff; cursor: pointer"
            class="btnColor"
          >
            {{ advanced ? '收起' : '展开' }}
            <i
              :class="advanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
            ></i>
          </a>
          <el-button
            type="primary"
            icon="icon iconfont iconchazhao1"
            @click="searchBrand"
            class="searchBtn"
          >
            <span>搜索</span>
          </el-button>
        </el-form-item>
      </el-form>
      <el-row>
        <div class="selectQy">
          已选<span>{{ enterpriseNum }}</span
          >个{{ isFjOrJs == 'NC' ? '企业' : '项目' }}
        </div>
      </el-row>
      <el-row>
        <el-table
          :data="tableList"
          v-loading="loading"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          highlight-current-row
          stripe
          style="border: 1px solid #dfe6ec"
          :row-key="recordId"
          ref="multipleTable"
          @select-all="selectAll"
          @select="selectionChange"
          :header-cell-class-name="cellClass"
        >
          <!-- @select="checkData"  -->
          <!-- @select-all="selectAll"  -->

          <el-table-column
            type="selection"
            width="60"
            :reserve-selection="true"
            :formatter="formatTd"
            align="left"
          ></el-table-column>
          <!-- <el-table-column prop="companyName" label="企业名称" v-if = "isFjOrJs == 'NC'" :key="1" :formatter=formatTd></el-table-column> -->
          <el-table-column
            label="企业名称"
            width="230"
            v-if="isFjOrJs == 'NC'"
            :key="1"
          >
            <template slot-scope="scope">
              <copyText
                :tableIndex="scope.$index"
                :copyTextName="scope.row.name"
                :columnName="'name'"
              ></copyText>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="projectName" label="项目名称" v-if = "isFjOrJs == 'CS'" :key="2" :formatter=formatTd></el-table-column> -->
          <el-table-column
            label="项目名称"
            width="230"
            v-if="isFjOrJs == 'CS'"
            :key="2"
          >
            <template slot-scope="scope">
              <copyText
                :tableIndex="scope.$index"
                :copyTextName="scope.row.projectName"
                :columnName="'projectName'"
              ></copyText>
            </template>
          </el-table-column>
          <el-table-column
            prop="areaName"
            label="区域"
            width="120"
            :formatter="formatTd"
          ></el-table-column>
          <el-table-column
            prop="industryName"
            label="行业"
            width="120"
            :formatter="formatTd"
          ></el-table-column>
          <el-table-column
            prop="investmentDesc"
            label="投资类型"
            v-if="isFjOrJs == 'CS'"
            :key="3"
            :formatter="formatTd"
            width="120"
          ></el-table-column>
          <el-table-column
            prop="statusDesc"
            label="状态"
            v-if="isFjOrJs == 'CS'"
            :key="6"
            :formatter="formatTd"
            width="100"
          ></el-table-column>
          <!-- <el-table-column prop="peopleTotal" label="单位评级"   v-if = "isFjOrJs == 'NC'" :key="4" :formatter=formatTd></el-table-column> -->
          <el-table-column
            prop="gradeLevel"
            label="项目评级"
            v-if="isFjOrJs == 'CS'"
            :key="5"
            :formatter="formatTd"
            width="100"
          ></el-table-column>
          <!-- 表格数据为空时，页面显示 -->
          <div slot="empty" v-show="isShow">
            <emptyTable emptyText="暂无数据"></emptyTable>
          </div>
        </el-table>
        <!-- filterField为搜索条件 -->
        <!-- getTableList为获取子组件的数据 -->
        <Pagination
          ref="pagination"
          @getList="getTableList"
          :filterField="isFjOrJs == 'NC' ? ncfilterField : filterField"
          :pageSize="pageSize"
          :pageSizes="pageSizes"
          :requestUrl="requestUrl"
        ></Pagination>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="dialogClose()" class="cancel"
          >取 消</el-button
        >
        <el-button
          type="primary"
          class="save"
          @click.native="save()"
          :loading="loading"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapActions, mapState } from 'vuex'

export default {
  name: 'addProject',
  data() {
    return {
      centerDialogVisible: true,
      requestUrl: '',
      filterField: {
        areaId: '',
        industryId: '',
        investment: '',
        gradeLevel: '',
        projectName: '',
        status: '',
      },
      ncfilterField: {
        bizAreaId: '',
        industryId: '',
        name: '',
      },
      //表格数据
      tableList: [],
      loading: false,
      isShow: false, //列表加载
      pageSize: 10,
      pageNo: 1,
      pageSizes: [10, 20, 30, 40],
      investmentTypeOptions: [],
      ncIndustryOptions: [],
      proGradeArr: [
        //     {
        //     code:"A",name:"A"
        // },{
        //     code:"B",name:"B"
        // },{
        //     code:"C",name:"C"
        // },
        // {
        //     code:"D",name:"D"
        // },
      ],
      checkedId: [],
      isAllSelect: false,
      checkedArr: [],
      enterpriseNum: '0',
      industryId: '',
      investment: '',
      gradeLevel: '',
      projectName: '',
      propsArr: { multiple: true },
      advanced: false,
    }
  },
  computed: {
    ...mapState([
      'areasOptions',
      'industryOptions',
      'industryOptionsNC',
      'statusOptions',
      'investmentOptions',
    ]),
  },
  props: {
    isFjOrJs: {
      type: String,
      required: true,
    },
    proList: {
      type: Array,
    },
  },
  watch: {
    // tableList: {
    //     handler (value) {
    //         if (this.isAllSelect) {
    //             let that = this
    //             let len =this.checkedArr.length
    //             value.forEach(row => {
    //                 for (let i = 0; i < len; i++) {
    //                     if (row.id === that.checkedArr[i].id) {
    //                     that.$refs.multipleTable.toggleRowSelection(row, false)
    //                     break
    //                 } else {
    //                     that.$refs.multipleTable.toggleRowSelection(row, true)
    //                 }
    //             }
    //             })
    //         }
    //     },
    // deep: true
    // }
  },
  created() {
    if (this.isFjOrJs == 'CS') {
      this.requestUrl = 'api-ps/creditProjectScore/expand/listbyconditions'
      //获取行业
      this.getIndustry({})
      this.getStatus({})
    } else {
      this.requestUrl = 'api-c/company/expand/listbyconditions'
      //获取行业
      this.getIndustrySelect()
    }
    this.getAreas({ areaId: this.$store.state.areaInfoArr.areaId })
    this.getTypeList()
    this.getLevelList('20') //项目评级配置
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
    })
    this.selectTableByUserId()
    if (this.proList.length > 0) {
      this.enterpriseNum = this.proList.length
      this.checkedArr = this.checkedArr.concat(this.proList)
    }
  },
  methods: {
    ...mapActions(['getAreas', 'getIndustry', 'getStatus']),
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    cellClass(row) {
      if (row.columnIndex === 0) {
        return 'disabledCheck'
      }
    },
    //获取选中的区域最后一级id
    getAreaId() {
      if (this.isFjOrJs == 'CS') {
        this.filterField.areaId = this.area[this.area.length - 1]
      } else {
        this.ncfilterField.bizAreaId = this.area[this.area.length - 1]
      }
    },
    getTableList(data) {
      this.tableList = data
      this.selectTableByUserId()
      this.loading = false
      if (this.tableList.length < 1) {
        this.isShow = true
      }
    },
    dialogClose() {
      // this.checkedArr= [];
      // this.$emit('changeData',this.checkedArr);
      this.$emit('closeDialog')
    },
    getTypeList() {
      this.axios({
        method: 'post',
        url: 'api-p/project/expand/findstatusbytype',
        data: { type: 'PROJECT_INVESTMENT' },
      }).then((res) => {
        if (!res.data.hasError) {
          // res.data.result.unshift({ code: "", name: "全部" });
          this.investmentTypeOptions = res.data.result
        }
      })
    },
    //列表多选选中事件

    recordId(row) {
      return row.id
    },
    selectionChange(rows, row) {
      console.log(rows, row, rows.indexOf(row))
      var selected = rows.length && rows.indexOf(row) !== -1
      if (selected) {
        if (this.proList.length > 0) {
          this.checkedArr.push(row)
        } else {
          this.checkedArr = rows
        }
      } else {
        this.checkedArr.forEach((item, i) => {
          if (item.id == row.id) {
            this.checkedArr.splice(i, 1)
          }
        })
      }
      this.enterpriseNum = this.checkedArr.length
    },
    selectAll(selection) {
      console.log('selection', selection)
      // this.isAllSelect = !this.isAllSelect;
      this.enterpriseNum = selection.length
      this.checkedArr = selection
      if (selection) {
        selection.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row, true)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    save() {
      var nameTit
      this.isFjOrJs == 'NC' ? (nameTit = '企业') : (nameTit = '项目')
      if (this.checkedArr.length > 30) {
        this.$message({
          message: nameTit + '数最大不超过30个',
          type: 'warning',
        })
        return
      }
      this.$emit('changeData', this.checkedArr)
      this.$emit('closeDialog')
    },
    selectTableByUserId() {
      this.$nextTick(() => {
        const userIdSelectList = this.proList
        const tableData = this.tableList
        for (var i = 0; i < userIdSelectList.length; i++) {
          for (var j = 0; j < tableData.length; j++) {
            if (userIdSelectList[i].id === tableData[j].id) {
              this.$refs.multipleTable.toggleRowSelection(tableData[j], true)
              // 删除已选中数据id
              // userIdSelectList.splice(i, 1)
            }
          }
        }
      })
    },
    searchBrand() {
      if (this.isFjOrJs == 'CS') {
        this.filterField.industryId = this.industryId.join(',')
        this.filterField.investment = this.investment.join(',')
        this.filterField.gradeLevel = this.gradeLevel.join(',')
        // this.filterField.status = this.status.join(",");
        this.filterField.projectName = this.projectName
      } else {
        if (this.industryId) {
          this.ncfilterField.industryId = this.industryId.join(',')
        }
        this.ncfilterField.name = this.projectName
      }

      this.$nextTick(function () {
        this.$refs.pagination.getTableListData()
      })
    },
    getIndustrySelect() {
      this.axios({
        method: 'post',
        url: 'api-bs/industry/base/firstindustry',
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.ncIndustryOptions = response.data.result
            } else {
              this.$message({
                message: '数据获取失败',
                type: 'error',
              })
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    getLevelList(type) {
      return this.axios({
        method: 'post',
        url: 'api-ps/creditLevel/expand/getCreditLevelList',
        data: {
          type,
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            const results = response.data.result
            results.forEach((v) => {
              v.name = v.gradeLevel
            })
            this.proGradeArr = results
            const otherLevel = { gradeLevel: 'O', name: '其他' }
            this.proGradeArr.push(otherLevel)
          } else {
            this.$message.error(response.data.errorMsg)
          }
        })
        .catch((error) => {
          if (error.response) {
            this.$message.error(error.response.data)
          }
        })
    },
    getIndustryId() {
      // if(this.filterField.industryId.length > 0){
      var industryId = this.industryId[this.industryId.length - 1]
      this.ncfilterField.industryId = industryId
      // }
    },
  },
}
</script>
<style scoped lang="less">
.btnBox {
  text-align: center;
}
.selectQy {
  font-size: 14px;
  color: red;
  margin-bottom: 12px;
}
.searchInputWidth /deep/ .el-form-item__content {
  height: initial !important;
}
.el-table /deep/.disabledCheck .cell .el-checkbox__inner {
  // display: none!important;
  left: 5px !important;
}
.el-table /deep/ .el-checkbox__inner {
  left: 7px !important;
}
// .el-table /deep/.disabledCheck .cell:before {
//     content: '全选当前页';
//     position: absolute;
//     top:12px;
//     right: 4px;
//     font-size:12px;
// }
</style>
